package com.example;

import com.example.container.thread;
import com.example.task.timetask;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;

@ComponentScan(basePackages = "com.example")
public class app {

    public static void main(String[] args) throws InterruptedException {
        // 启动 Spring IoC 容器（基于注解）
        var context = new AnnotationConfigApplicationContext(thread.class);

        // 从容器获取线程池
        var executor = context.getBean("customThreadPool", ExecutorService.class);

        // 从容器获取任务对象
        var task = context.getBean(timetask.class);

        System.out.println(" Spring 容器已启动，提交定时任务...");

        // 提交任务到线程池
        executor.submit(task);

        // 等待65秒，让任务执行完
        Thread.sleep(65000);

        // 停止任务（优雅关闭）
        task.stop();

        // 关闭线程池
        executor.shutdown();
        try {
            if (!executor.awaitTermination(5, TimeUnit.SECONDS)) {
                executor.shutdownNow();
            }
        } catch (InterruptedException e) {
            executor.shutdownNow();
            Thread.currentThread().interrupt();
        }

        System.out.println(" 所有任务已结束，程序退出。");

        // 关闭 Spring 容器
        context.close();
    }
}